import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { CoreConst } from '@ibiz-template/core';
import { Button, Form, Input } from 'antd';
import { setCookie } from 'qx-util';
import { useNavigate, useSearchParams } from 'react-router-dom';
import './login.scss';

/**
 * 登录页面
 *
 * @author chitanda
 * @date 2022-07-18 10:07:58
 * @class Login
 * @extends {Component}
 */
function Login() {
  const defaultValues = {
    username: 'zjbjadmin',
    password: '123456',
  };

  const navigate = useNavigate();

  const searchParams = useSearchParams();
  const redirect = searchParams[0].get('redirect');

  const onFinish = async (values: any) => {
    const res = await ibiz.auth.v7login(values.username, values.password);
    if (res.ok) {
      const { data } = res;
      if (data && data.token) {
        setCookie(CoreConst.TOKEN, data.token, 7, true);
      }
      let path = '';
      if (!redirect) {
        path = '/';
      } else if (redirect.startsWith('/')) {
        path = redirect;
      } else if (redirect.startsWith(location.origin)) {
        path = redirect.replace(`${location.origin}${location.pathname}#`, '');
      } else {
        throw new Error('redirect url is invalid');
      }
      navigate(path, { replace: true });
    }
  };

  return (
    <div className='login-view'>
      <Form
        name='normal_login'
        className='login-form'
        initialValues={defaultValues}
        onFinish={onFinish}
      >
        <Form.Item
          name='username'
          rules={[{ required: true, message: 'Please input your Username!' }]}
        >
          <Input
            prefix={<UserOutlined className='site-form-item-icon' />}
            placeholder='请输入用户名'
          />
        </Form.Item>
        <Form.Item
          name='password'
          rules={[{ required: true, message: 'Please input your Password!' }]}
        >
          <Input
            prefix={<LockOutlined className='site-form-item-icon' />}
            type='password'
            placeholder='请输入密码'
          />
        </Form.Item>

        <Form.Item>
          <Button
            type='primary'
            htmlType='submit'
            className='login-form-button'
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default Login;
